package com.hilihili.mq.consumer;

import com.hilihili.config.TranscodeConfig;
import com.hilihili.domain.entity.Video;
import com.hilihili.mapper.VideoMapper;
import com.hilihili.mq.config.VideoTranscodeMqConfig;
import com.hilihili.mq.message.VideoTranscodeMessage;
import com.hilihili.transcode.AbstractTranscodeCommand;
import com.hilihili.transcode.FFmpegUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 小文件队列消费者处理逻辑
 *
 * @author machi
 * @date 2024/01/21
 */
@Component
@RabbitListener(queuesToDeclare = @Queue(VideoTranscodeMqConfig.DIRECT_VIDEO_TRANSCODE_SMALL_FILE_QUEUE))
@Slf4j
public class VideoTranscodeSmallFileConsumer {


    @Autowired
    AbstractTranscodeCommand command;
    @Autowired
    VideoMapper videoMapper;
    @Autowired
    TranscodeConfig transcodeConfig;

    @RabbitHandler
    @Transactional(rollbackFor = Exception.class)
    public void process(VideoTranscodeMessage videoTranscodeMessage) throws IOException, InterruptedException {

        String videoId = videoTranscodeMessage.getVideoId();
        log.info(videoId);
        //查询video转码文件是否存在 不存在则转码  防止重复消费消息
        Video video = videoMapper.selectVideoById(Long.parseLong(videoId));
        if (!Files.exists(Paths.get(transcodeConfig.getSource() + video.getLink()))){
            String tempDir = videoTranscodeMessage.getTempDir();
            String targetDir = videoTranscodeMessage.getTargetDir();
            log.info("开始转码");
            FFmpegUtils fFmpegUtils = new FFmpegUtils("small");
            fFmpegUtils.transcodeToM3u8(tempDir, targetDir,command);
            //是定时任务则不设置视频已发布
            if (!videoTranscodeMessage.isTiming()) {
                videoMapper.publishVideoByLink(videoTranscodeMessage.getFilePath());
            }
            if (Files.exists(Paths.get(tempDir))){
                //删除临时文件
                Files.delete(Paths.get(tempDir));
            }
        }
    }
}
